const express = require('express')
const router = express.Router()
const db = require('../db')
const consts = require('../../consts/Consts')
/**
 * @api {get} http://127.0.0.1:3658/usermobile/login 手机端登录
 * @apiDescription 手机端登录
 * @apiName login
 * @apiGroup 手机用户
 * @apiParam (参数) {String} phoneNumber 手机号
 * @apiParam (参数) {String} pwd 密码
 *
 * @apiSuccess {int} code 状态码.
 * @apiSuccess {String} result  json数据.
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 20000,
 *      "result" : {}
 *
 *  }
 * @apiVersion 1.0.0
 */
router.get('/login', (req, res, err) => {
  const phoneNumber = req.query.phoneNumber
  const pwd = req.query.pwd
  db.UserMobileDb.get(phoneNumber, (err, user) => {
    if (err) throw err
    // user:undefined
    // user:{ phoneNumber: '11111111111', pwd: '123456' }
    console.log('user:%o', user)
    if (user == null || user.phoneNumber == null) {
      res.send({
        code: consts.RES_LOGIN_PHONENUMBER_ERROR,
        result: {}
      })
    } else if (pwd !== user.pwd) {
      res.send({
        code: consts.RES_LOGIN_PWD_ERROR,
        result: {}
      })
    } else {
      res.send({
        code: consts.RES_OK,
        result: {
          phoneNumber: user.phoneNumber,
          name: user.name
        }
      })
    }
  })
})

module.exports = router
